<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Records;
use app\admin\model\Xsjsdan as XsjsdanModel;
use app\BaseController;
use app\lib\Excel;
use think\Request;
use app\admin\model\Cgjsdan as CgjsdanModel;

class Cgjsdan extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $page = input('page', 1, 'intval');
        $list = CgjsdanModel::list($page);
        return show(config('status.success'), '获取列表', $list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $dataparam=$request->post();
        $param = $params = json_decode($dataparam['param'],true);
        if(empty($param)){
            return show(config('status.error'), '没有选中要结算的单据!');
        }
        $xiangtong = $this->FetchRepeatMemberInArray($param);
        /*$ghgs_num = array_unique(array_column($param,'ghgs'));
        if(count($ghgs_num)>1){
            return show(config('status.error'), '您选中的采购供货公司不是同一家!');
        }
        $shdw_num = array_unique(array_column($param,'shdw'));
        if(count($shdw_num)>1){
            return show(config('status.error'), '您选中的采购收货公司不是同一家!');
        }
        $pinming_num = array_unique(array_column($param,'value'));
        if(count($pinming_num)>1){
            return show(config('status.error'), '您选中的品名不是同一个!');
        }
        $sksjarr = array_column($param,'sksj');
        sort($sksjarr);
        $sksj_num = count($sksjarr);
        $data = [];
        if($sksj_num>1){
            $data['ghtime'] = $sksjarr[0]."~".$sksjarr[$sksj_num-1];
        }else{
            $data['ghtime'] = $sksjarr[0];
        }*/

        $result=false;
        if(!empty($xiangtong) && is_array($xiangtong)){
            foreach ($xiangtong as $k=>$v){$datat['cgid']='';$datat['cg_num']=0;$datat['ghtime']='';
                foreach ($param as $key=>$item){
                    if($v['ghgs']==$item['ghgs'] && $v['shdw']==$item['shdw'] && $v['value']==$item['value']){
                        $datat['ghgs'] = $item['ghgs'];
                        $datat['shdw'] = $item['shdw'];
                        $datat['supply_name'] = $item['supply_name'];
                        $datat['receive_name'] = $item['receive_name'];
                        $datat['value'] = $item['value'];
                        $datat['product_name'] = $item['product_name'];
                        $datat['cg_num'] += $item['cgsl'];
                        $datat['cg_price'] = 0;
                        $datat['total_amount'] = 0;
                        $datat['cj_contract_code'] = '';
                        $datat['cgid'] .="{$item['id']},";
                        $datat['user_name'] = $item['user_name'];
                        $datat['ghtime'] .= "{$item['sksj']},";
                        //$dataalike[] = $datat;
                        unset($param[$key]);
                    }
                }
                $datat['cgid'] = trim( $datat['cgid'],','); $datat['ghtime'] = trim($datat['ghtime'],',');
                $result = CgjsdanModel::add($datat);
                $dataalike[] = $datat;
                unset($datat);
            }
        }
        if(!empty($param) && is_array($param)){
            foreach ($param as $key=>$item){
                $data['ghgs'] = $item['ghgs'];
                $data['shdw'] = $item['shdw'];
                $data['supply_name'] = $item['supply_name'];
                $data['receive_name'] = $item['receive_name'];
                $data['value'] = $item['value'];
                $data['product_name'] = $item['product_name'];
                $data['cg_num'] = $item['cgsl'];
                $data['cg_price'] = 0;
                $data['total_amount'] = 0;
                $data['cj_contract_code'] = '';
                $data['cgid'] =$item['id'];
                $data['user_name'] = $item['user_name'];
                $data['ghtime'] = $item['sksj'];
                $result = CgjsdanModel::add($data);
            }
        }
        $datas = [];
        if($result){
            foreach ($params as $k=>$v){
                $datas['id']=$v['id'];
                $datas['is_cgjs'] = 1;
                Records::edit($datas);
            }
        }
        if($result){
            return show(config('status.success'), '操作成功!');
        }else {
            return show(config('status.error'), '操作失败!');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $detail = CgjsdanModel::detail($id);
        $datas = [
            [
                'title' => '销售结算单',
                'signature'=>'部门签章：',
                'rows'  => [
                    [
                        '部门签章：', ' ', ' ', '  ', '', ' ', ' ',' '
                    ],
                    [
                        '序号', '销售时间', '品名', '采购数量（吨）', '采购单价（元）', '采购金额（元）', '采购合同号','备注'
                    ],
                    [
                        "1", "{$detail['ghtime']}", "{$detail['product_name']}", "{$detail['cg_num']}", "{$detail['cg_price']}", "{$detail['total_amount']}", "{$detail['cj_contract_code']}",""
                    ],
                    [
                        " ", " ", " ", " ", " ", " ", " "," "
                    ],
                    [
                        " ", " ", " ", " ", " ", " ", " "," "
                    ],
                    [
                        "合计", " ", " ", "{$detail['cg_num']}", " ", "{$detail['total_amount']}", " "," "
                    ],
                    [
                        "终端用户", "{$detail['user_name']}", " ", "", " ", "", " "," "
                    ],
                    [
                        "制表:", " ", " ", "复审:", " ", "", "制表日期:"," "
                    ]
                ]
            ]
        ];
        $excel = new Excel();
        $excel->exportExecl1($datas);exit();
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        //
        $data=$request->post();
        $result = CgjsdanModel::edit($data);
        if($result){
            return show(config('status.success'), '操作成功!');
        }else {
            return show(config('status.error'), '操作失败!');
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        $result = CgjsdanModel::del($id);
        if($result){
            return show(config('status.success'), '操作成功!');
        }else{
            return show(config('status.error'), '操作失败!');
        }
    }
    public function xiangtong($param){
        $dataxiantong = [];
        $databutong = [];
        foreach ($param as $key=>$val){
            if($param[$key]['ghgs']==$param[$key+1]['ghgs'] && $param[$key]['shdw']==$param[$key+1]['shdw'] && $param[$key]['value']==$param[$key+1]['value']){
                $dataxiantong[] = $val;
            }else{
                $databutong[] = $val;
            }
        }
        print_r($dataxiantong);print_r($databutong);
        return true;
    }
    public function FetchRepeatMemberInArray($array) {
        $len = count ($array);
        $dataxiantong = [];
        for($i = 0; $i < $len; $i ++) {
            for($j = $i + 1; $j < $len; $j ++) {
                if ($array[$i]['ghgs'] == $array [$j]['ghgs'] && $array[$i]['shdw'] == $array [$j]['shdw'] && $array[$i]['value'] == $array [$j]['value']) {
                    $dataxiantong[] = $array [$i];
                    break;
                }
            }
        }
        return $dataxiantong;
    }
}
